/**
 * 
 */
package com.geezdata.cps.sdk3rd.wechat.method;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.geezdata.cps.base.enums.ErrorCode;
import com.geezdata.cps.base.exceptions.MyException;
import com.geezdata.cps.base.utils.HttpClientUtil;
import com.geezdata.cps.sdk3rd.wechat.request.WechatAccessTokenRequest;
import com.geezdata.cps.sdk3rd.wechat.response.WechatAccessTokenResult;
import com.google.common.collect.Maps;

/**
 * @author sszheng
 * @date 创建时间：2018年3月30日 上午10:10:44
 *
 */
public class WechatAccessToken implements Wechat<WechatAccessTokenRequest, WechatAccessTokenResult> {
	private static final Logger logger = LoggerFactory.getLogger(WechatAccessToken.class); 
	
	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?";

	@Override
	public WechatAccessTokenResult execute(WechatAccessTokenRequest request) {
		Map<String, Object> params = prepareParams(request);
		
		String rspStr = null;
		try {
			rspStr = HttpClientUtil.get(ACCESS_TOKEN_URL, params);
			logger.info("WechatAccessToken result: " + rspStr);
			if (rspStr == null) {
				logger.info("WechatAccessToken url {}", ACCESS_TOKEN_URL);
	        	logger.info("WechatAccessToken params {}", JSON.toJSONString(params));
	        	throw new MyException(ErrorCode.INTERNAL_SERVER_ERROR.getCode(), "ACCESS_TOKEN_URL failed "); 
			}
			JSONObject jsonObject = JSONObject.parseObject(rspStr);
			WechatAccessTokenResult result = JSONObject.toJavaObject(jsonObject, WechatAccessTokenResult.class);
			return result;
		} catch (Exception e) {
			logger.error("WechatAccessToken::execute failed url {}, params {}", ACCESS_TOKEN_URL, JSON.toJSONString(params));
		}
		return null;
	}

	private Map<String, Object> prepareParams(WechatAccessTokenRequest request) {
		Map<String, Object> params = Maps.newHashMap();
		params.put("grant_type", request.getGrantType());
		params.put("appid", request.getAppId());
		params.put("secret", request.getAppSecret());
		return params;
	}

}
